/**
 * Resize function without multiple trigger
 * 
 * Usage:
 * $(window).smartresize(function(){  
 *     // code here
 * });
 */
(function($, sr) {
	// debouncing function from John Hann
	// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
	var debounce = function(func, threshold, execAsap) {
		var timeout;

		return function debounced() {
			var obj = this, args = arguments;
			function delayed() {
				if (!execAsap)
					func.apply(obj, args);
				timeout = null;
			}

			if (timeout)
				clearTimeout(timeout);
			else if (execAsap)
				func.apply(obj, args);

			timeout = setTimeout(delayed, threshold || 100);
		};
	};

	// smartresize 
	jQuery.fn[sr] = function(fn) {
		return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr);
	};

})(jQuery, 'smartresize');
/**
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

var CURRENT_URL = window.location.href.split('#')[0].split('?')[0], 
$BODY = $('body'), 
$MENU_TOGGLE = $('#menu_toggle'), 
$SIDEBAR_MENU = $('#sidebar-menu'), 
$SIDEBAR_FOOTER = $('.sidebar-footer'), 
$LEFT_COL = $('.left_col'), 
$RIGHT_COL = $('.right_col'), 
$NAV_MENU = $('.nav_menu'), 
$FOOTER = $('footer');
$SIDEBAR_FOOTER=$(".sidebar-footer")


function LoadAjaxContent(url){
	//alert(url);
	$.ajax({
		mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
		url: url,
		type: 'POST',
		dataType: "html",
		async: false,
		success: function(data) {
			$('#ajax_content').html(data);
		},
		error: function (jqXHR, textStatus, errorThrown) {
			alert(errorThrown);
		}
	});
}

// 侧边栏事件绑定
function init_sidebar() {
	// TODO: This is some kind of easy fix, maybe we can improve this
	var setContentHeight = function() {
		// reset height
		$RIGHT_COL.css('min-height', $(window).height());

		var bodyHeight = $BODY.outerHeight(), footerHeight = $BODY
				.hasClass('footer_fixed') ? -10 : $FOOTER.height(), leftColHeight = $LEFT_COL
				.eq(1).height()
				+ $SIDEBAR_FOOTER.height(), contentHeight = bodyHeight < leftColHeight ? leftColHeight
				: bodyHeight;

		// normalize content
		contentHeight -= $NAV_MENU.height() + footerHeight;

		$RIGHT_COL.css('min-height', contentHeight);
	};

	$SIDEBAR_MENU.find('a').on('click', function(ev) {
		
		ev.preventDefault();
		var url = $(this).attr('href');
		if(url!=undefined && url.length>0){
			window.location.hash = url;
			LoadAjaxContent(url);
		}
				
		var $li = $(this).parent();
		if ($li.is('.active')) {
			$li.removeClass('active active-sm');
			$('ul:first', $li).slideUp(function() {
				setContentHeight();
			});
		} else {
			// prevent closing menu if we are on child menu
			if (!$li.parent().is('.child_menu')) {
				$SIDEBAR_MENU.find('li').removeClass('active active-sm');
				$SIDEBAR_MENU.find('li ul').slideUp();
			} else {
				if ($BODY.is(".nav-sm")) {
					$SIDEBAR_MENU.find("li").removeClass("active active-sm");
					$SIDEBAR_MENU.find("li ul").slideUp();
				}
			}
			$li.addClass('active');

			$('ul:first', $li).slideDown(function() {
				setContentHeight();
			});
		}
	});

	// toggle small or large menu 
	$MENU_TOGGLE.on('click', function() {
		console.log('clicked - menu toggle');

		if ($BODY.hasClass('nav-md')) {
			$SIDEBAR_MENU.find('li.active ul').hide();
			$SIDEBAR_MENU.find('li.active').addClass('active-sm').removeClass(
					'active');
		} else {
			$SIDEBAR_MENU.find('li.active-sm ul').show();
			$SIDEBAR_MENU.find('li.active-sm').addClass('active').removeClass(
					'active-sm');
		}

		$BODY.toggleClass('nav-md nav-sm');

		setContentHeight();
	});

	
	// recompute content when resizing
	$(window).smartresize(function() {
		setContentHeight();
	});

	setContentHeight();

	// fixed sidebar
	if ($.fn.mCustomScrollbar) {
		$('.menu_fixed').mCustomScrollbar({
			autoHideScrollbar : true,
			theme : 'minimal',
			mouseWheel : {
				preventDefault : true
			}
		});
	}
};
// /Sidebar

// 折叠按钮事件绑定			
function init_collapse() {
	$("#ajax_content").on('click','.collapse-link',function() {
		var $BOX_PANEL = $(this).closest('.x_panel'), 
		$ICON = $(this).find('i'), 
		$BOX_CONTENT = $BOX_PANEL.find('.x_content');

		// fix for some div with hardcoded fix class
		if ($BOX_PANEL.attr('style')) {
			$BOX_CONTENT.slideToggle(200,function() {
					$BOX_PANEL.removeAttr('style');
				});
		} else {
			$BOX_CONTENT.slideToggle(200);
			$BOX_PANEL.css('height', 'auto');
		}
		
		$ICON.toggleClass('fa-chevron-up fa-chevron-down');
	});

	$("#ajax_content").on('click','.close-link',function() {
		var $BOX_PANEL = $(this).closest('.x_panel');
		$BOX_PANEL.remove();
	});
}

// tooltip绑定事件
function init_tooltip() {
	$('[data-toggle="tooltip"]').tooltip({
		container : 'body'
	});
	$SIDEBAR_FOOTER.find("a").first().on('click',function(ev){
		ev.preventDefault();
		var url = $(this).attr('href');
		if(url!=undefined && url.length>0){
			window.location.hash = url;
			LoadAjaxContent(url);
		}
	})
}

// 表格初始化绑定事件
function init_table(){
	
	$("#ajax_content").on('ifChecked','table input', function() {
		checkState = '';
		$(this).parent().parent().parent().addClass('selected');
		countChecked();
	});
	$("#ajax_content").on('ifUnchecked','table input', function() {
		checkState = '';
		$(this).parent().parent().parent().removeClass('selected');
		countChecked();
	});

	var checkState = '';

	$("#ajax_content").on('ifChecked','.bulk_action input', function() {
		checkState = '';
		$(this).parent().parent().parent().addClass('selected');
		countChecked();
	});
	$("#ajax_content").on('ifUnchecked','.bulk_action input', function() {
		checkState = '';
		$(this).parent().parent().parent().removeClass('selected');
		countChecked();
	});
	
	$("#ajax_content").on('ifChecked','.bulk_action input#check-all', function() {
		checkState = 'all';
		countChecked();
	});
	$("#ajax_content").on('ifUnchecked','.bulk_action input#check-all', function() {
		checkState = 'none';
		countChecked();
	});
}

function countChecked() {
	if (checkState === 'all') {
		$(".bulk_action input[name='table_records']").iCheck('check');
	}
	if (checkState === 'none') {
		$(".bulk_action input[name='table_records']").iCheck('uncheck');
	}

	var checkCount = $(".bulk_action input[name='table_records']:checked").length;

	if (checkCount) {
		$('.column-title').hide();
		$('.bulk-actions').show();
		$('.action-cnt').html(checkCount + ' Records Selected');
	} else {
		$('.column-title').show();
		$('.bulk-actions').hide();
	}
}


//hover and retain popover when on popover content
var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj) {
	var self = obj instanceof this.constructor ? obj
			: $(obj.currentTarget)[this.type](this.getDelegateOptions()).data(
					'bs.' + this.type);
	var container, timeout;

	originalLeave.call(this, obj);

	if (obj.currentTarget) {
		container = $(obj.currentTarget).siblings('.popover');
		timeout = self.timeout;
		container.one('mouseenter', function() {
			//We entered the actual popover – call off the dogs
			clearTimeout(timeout);
			//Let's monitor popover content instead
			container.one('mouseleave', function() {
				$.fn.popover.Constructor.prototype.leave.call(self, self);
			});
		});
	}
};

$('body').popover({
	selector : '[data-popover]',
	trigger : 'click hover',
	delay : {
		show : 50,
		hide : 400
	}
});

 /* form表单验证 */
function init_validator() {
	
	if(typeof (validator) === 'undefined'){ return; }

	validator.message.date = '不是有效的日期';

	// validate a field on "blur" event, a 'select' on 'change' event & a '.reuired' classed multifield on 'keyup':
	
	$('#ajax_content')
	.on('blur', 'form input[required],form input.optional,form select.required', validator.checkField)
	.on('change', 'form select.required', validator.checkField)
	.on('keypress', 'form input[required][pattern]', validator.keypress);

	$('#ajax_content').on('keyup blur', '.multi.required input', function() {
		validator.checkField.apply($(this).siblings().last()[0]);
	});

	$('#ajax_content').on('submit','form',function(e) {
		e.preventDefault();
		var submit = true;
		
		if (!validator.checkAll($(this))) {
		  submit = false;
		}

		if (submit)
			this.submit();

		return false;
	});
};

$(function() {
	// 侧边栏事件绑定
	init_sidebar();
	// tooltip绑定事件
	init_tooltip();
	// 折叠按钮事件绑定	
	init_collapse();
	// 表格初始化绑定事件
	init_table();
	// form表单验证
	init_validator();

});
